package com.common.www.controller.programme;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.programme.XfgcPrecipitate;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.programme.XfgcPrecipitateService;
import com.common.www.service.project.ProjectService;
import com.common.www.service.project.XfgcBasicService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/xfgcPrecipitate"})
@Api(tags = "MGT 消防工程数据沉淀接口")
public class MGTXfgcPrecipitateController extends DefaultCrudController<XfgcPrecipitate, Long> {
    @Autowired
    private XfgcPrecipitateService service;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private XfgcBasicService xfgcBasicService;

    protected IBaseService getService() {
        return service;
    }


    @ApiOperation(value = "生成 定标 标阶段的数据沉淀分析", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/generatePrecipitate", produces = {"application/json"}, method = RequestMethod.POST)
    public Result generatePrecipitate(Long projectId, Long choiceProjectId,Long choiceSupplyCompanyId) throws InvocationTargetException, IllegalAccessException {
        if (choiceProjectId == null || choiceSupplyCompanyId == null){
            //再次生成时删除原来的数据
            service.getRepository().deleteByFlagAndProjectId(1,projectId);
            service.handlePrecipitate(projectId);
        }else {
            //添加对比项目
            service.handlePrecipitateToProject(projectId,choiceProjectId,choiceSupplyCompanyId);
        }
        return R.ok();
    }


    @ApiOperation(value = "生成定标阶段的沉淀分析数据时选择对比项目", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/choiceProject", produces = {"application/json"}, method = RequestMethod.POST)
    public Result choiceProject(Long projectId,String province,String city) throws InvocationTargetException, IllegalAccessException {
        return R.ok(service.choiceProject(projectId));
    }

    @ApiOperation("编辑差异信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        XfgcPrecipitate contrast = JSON.parseObject(json, XfgcPrecipitate.class);
        if (contrast.getId() == null) {
            service.saveAndFlush(contrast);
        } else {
            // 如果 id 不为空，则从数据库中获取现有对象
            XfgcPrecipitate existing = service.getByIdLogic(contrast.getId());
            if (existing != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(contrast, existing, "id");
                // 然后保存更新后的对象
                service.saveAndFlush(existing);
            } else {
                // 如果不存在，则保存解析出来的对象
                service.saveAndFlush(contrast);
            }
        }
        return R.ok(contrast);
    }


    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            XfgcPrecipitate contrast = service.findOne(ids[i]);
            if(contrast!=null){
                contrast.setFlag(0);
                service.save(contrast);
            }
        }
        return R.ok();
    }

    @ApiOperation(value = "查询供应商定标沉淀信息", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getDbList", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getDbList(Long projectId,String xiTong,String yeTai) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        if (StringUtils.isNotEmpty(xiTong)){
            hashMap.put("xiTong", xiTong);
        }
        if (StringUtils.isNotEmpty(yeTai)){
            hashMap.put("yeTai", yeTai);
        }
        List<XfgcPrecipitate> dbList = service.getListLogic(hashMap, null);
        //按供应商分组
        List<Map<String, Object>> mapList = service.getXfgcAssembleSjcdList(dbList);
        return R.ok(mapList);
    }


    @ApiOperation("导出定标阶段数据沉淀")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportDb", method = RequestMethod.GET)
    public Result exportDb(Long projectId) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        List<XfgcPrecipitate> dbList = service.getListLogic(hashMap, null);
        List<Map<String, Object>> mapList = service.getXfgcAssembleSjcdList(dbList);
        //设置导出信息
        String fileName = dbList.get(0).getProject().getName();
        XSSFWorkbook workbook = service.exportDb(mapList);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode( fileName+"数据沉淀(定标)-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }




}

